跳到主要内容

Python 中的字符串类型

字符串方法

# 使用数组读取字符
a = "Hello, World!"
print(a[1])


# 裁切字符
b = "Hello, World!"
print(b[2:5])


# 负的索引(倒着裁切)获取从位置 5 到位置 1 的字符,从字符串末尾开始计数
b = "Hello, World!"
print(b[-5:-2])


# 字符串长度
a = "Hello, World!"
print(len(a))


# 删除开头和结尾的空白字符
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"


# 返回小写的字符串
a = "Hello, World!"
print(a.lower())


# 返回大写的字符串
a = "Hello, World!"
print(a.upper())


# 替换字符串
a = "Hello, World!"
print(a.replace("World", "Kitty"))


# 分隔符的实例时将字符串拆分为子字符串
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']


# 检查字符串中是否存在特定短语或字符(in 或者 not in 关键字)
txt = "China is a great country"
x = "ina" in txt
print(x)


# 组合字符串和数字(因为字符串和别的类型无法直接字符拼接)
a = 3
b = 567
b = 49.95
txt = "I want {} pieces of item {} for {} dollars."
# 或者 "I want to pay {2} dollars for {0} pieces of item {1}." 指定次序
print(txt.format(a, b, c))

字符串格式化

就是模板字符,基本所有语言都有 使用 format() 方法可以传入字符串

# 新版可以直接在字符前面加个 f
print(f'ip: {ip} port: {port}')
price = 52
txt = "The price is {} dollars"


# 将价格格式化为带有两位小数的数字:
txt = "The price is {:.2f} dollars"

# 多个值
quantity = 3
itemno = 567
price = 52
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))


print(txt.format(price))

正则表达式

RegEx 模块

import re

txt = "China is a great country"
x = re.search("^China.*country$", txt)

# 需要取得第一个(group() 返回被 RE 匹配的字符串)
# #group(0) 就是匹配的整个结果
# #group(1) 是第一个group的值
re.search('[0-9].?[0-9]', it.xpath('.//p/text()').get()).group(0)

matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter

包含的函数

函数描述
findall返回包含所有匹配项的列表
search如果字符串中的任意位置存在匹配,则返回 Match 对象
split返回在每次匹配时拆分字符串的列表
sub用字符串替换一个或多个匹配项

元字符(用于匹配的字符)